<?php

namespace App\Http\Controllers\Admin;

use App\Http\Models\Nav;
use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;


class NavController extends CommonController
{
    // get admin/nav
    public function index()
    {
        $nav = Nav::orderBy('nav_order','asc')->get();
        return view('admin.nav.index',compact('nav'));
    }

    // DELETE admin/nav/{id} 删除友情链接
    public function destroy($nav_id)
    {
        $res = Nav::where('nav_id',$nav_id)->delete();
        if($res){
            return array('status'=>0,'msg'=>'自定义导航删除成功!');
        }else{
            return array('status'=>1,'msg'=>'自定义导航删除失败!');
        }
    }

    // ajax 修改排序
    public function changeOrder()
    {
        $input = Input::all();
        $field = Nav::find($input['nav_id']);
        $field->nav_order = $input['nav_order'];
        $res = $field->update();
        $data = array();
        if($res){
            $data['status'] = 0;
            $data['msg'] = '排序修改成功!';
        }else{
            $data['status'] = 1;
            $data['msg'] = '排序修改失败,请稍后再试!';

        }
        return $data;

    }

    // get admin/nav/create
    public function create()
    {
        return view('admin.nav.add');
    }

    // POST admin/nav 入库
    public function store()
    {
        $input = Input::except('_token');
        // Validator 验证
        $rules = ['nav_name'=>'required','nav_url'=>'required','nav_alias'=>'required'];
        $message = ['nav_name.required'=>'自义定导航名称不能为空!','nav_url.required'=>'URL不能为空!','nav_alias.required'=>'导航别名不能为空!'];
        $validator = Validator::make($input,$rules,$message);
        if($validator->passes()){
            $res = Nav::create($input);
            if($res){
                return redirect('admin/nav');
            }else{
                return back()->with('errors','自定义导航添加失败!');
            }
        }else{
            return back()->withErrors($validator);
        }
    }

    // 编辑 get admin/nav/{id}/edit
    public function edit($nav_id)
    {
        $field = Nav::find($nav_id);
        return view('admin.nav.edit',compact('field'));
    }

    // PUT|PATCH admin/nav/{id} 更新分类
    public function update($nav_id)
    {
        $input = Input::except('_token','_method');
        // Validator 验证
        $rules = ['nav_name'=>'required','nav_url'=>'required','nav_alias'=>'required'];
        $message = ['nav_name.required'=>'自义定导航名称不能为空!','nav_url.required'=>'URL不能为空!','nav_alias.required'=>'导航别名不能为空!'];
        $validator = Validator::make($input,$rules,$message);
        if($validator->passes()){
            $res = Nav::where('nav_id',$nav_id)->update($input);
            if($res){
                return redirect('admin/nav');
            }else{
                return back()->with('errors','自定义导航更新失败!');
            }
        }else{
            return back()->withErrors($validator);
        }

    }

}
